﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using VXCompany.SilverlightLogging.ServiceProxy;

namespace VXCompany.SilverlightLogging.MVVM.Models.Stores
{
	/// <summary>
	/// Stores ExceptionMessage items in IsolatedStorageSettings.ApplicationSettings.
	/// </summary>
	public class ApplicationStore : Store
	{
		protected const string APPSETTINGS_KEY = "ExceptionMessagesList";

		/// <summary>
		/// Creates new instance. Initializes store.
		/// </summary>
		public ApplicationStore()
		{
			Initialize();
		}

		/// <summary>
		/// Gets or sets the store dictionary.
		/// </summary>
		protected IDictionary<string, object> PlatformStore { get; set; }

		#region IStore Members

		/// <summary>
		/// Prepares store for use.
		/// </summary>
		protected override void InitializeImpl()
		{
			try
			{
				this.PlatformStore = IsolatedStorageSettings.ApplicationSettings;
				IsStorageAvailable = true;
			}
			catch (IsolatedStorageException)
			{
				IsStorageAvailable = false;
			}
		}

		/// <summary>
		/// Returns all ExceptionMessage items from the store.
		/// </summary>
		/// <returns></returns>
		protected override IEnumerable<ExceptionMessage> GetItemsFromStore()
		{
			if (PlatformStore.ContainsKey(APPSETTINGS_KEY))
			{
				return PlatformStore[APPSETTINGS_KEY] as ObservableCollection<ExceptionMessage>;
			}

			return null;
		}

		/// <summary>
		/// Saves changes.
		/// </summary>
		protected override void SaveImpl()
		{
			if (!PlatformStore.ContainsKey(APPSETTINGS_KEY))
			{
				PlatformStore.Add(APPSETTINGS_KEY, InnerList);
			}
			else
			{
				PlatformStore[APPSETTINGS_KEY] = InnerList;
			}
			IsolatedStorageSettings.ApplicationSettings.Save();
		}

		#endregion
	}
}
